package com.itheima.day02.Demo04;

public class MyRunnable implements Runnable{
    private static int ticketCount=100;
    @Override
    public void run() {
        while (true){
            if ("窗口一".equals(Thread.currentThread().getName())){
                boolean result = synchronizedMethod();
                if(result){
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())){
                synchronized (MyRunnable.class){
                    if(ticketCount==0){
                        break;
                    }else{
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName()+"在买票，还剩"+ticketCount+"张");
                    }
                }
            }
        }

    }

    private static synchronized boolean synchronizedMethod() {
        if (ticketCount==0){
            return true;
        }else{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName()+"在买票，还剩"+ticketCount+"张");
            return false;

        }
    }
}
